package com.zmx.patientend.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.giftedcat.easylib.selector.MultiImageSelector;
import com.zmx.patientend.BaseActivity;
import com.zmx.patientend.R;
import com.zmx.patientend.adapter.NineGridAdapter;
import com.zmx.patientend.listener.OnAddPicturesListener;
import com.zmx.patientend.utils.AllUtil;
import com.zmx.patientend.utils.BitmapUtil;
import com.zmx.patientend.view.util.MySharedPreferences;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 时间：2020/7/16 17:27
 * 功能：发布朋友圈
 */
public class ReleaseFriendsActivity extends BaseActivity {

    @BindView(R.id.editText)
    EditText editText;
    @BindView(R.id.submit_feedback)
    Button submitFeedback;

    private RecyclerView rvImages;
    NineGridAdapter adapter;
    private int maxNum = 9;
    Unbinder unbinder;
    List<String> mSelect;
    List<String> select;//图片路径
    private static final int REQUEST_IMAGE = 2;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_release_friends;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);

        mSelect = new ArrayList<>();
        rvImages = findViewById(R.id.rv_images);
        rvImages.setLayoutManager(new GridLayoutManager(this, 3));
        adapter = new NineGridAdapter(this, mSelect, rvImages);
        adapter.setMaxSize(maxNum);
        rvImages.setAdapter(adapter);
        adapter.setOnAddPicturesListener(new OnAddPicturesListener() {
            @Override
            public void onAdd() {
                pickImage();
            }
        });

    }


    /**
     * 选择添加图片
     */
    private void pickImage() {

        MultiImageSelector selector = MultiImageSelector.create(mActivity);
        selector.showCamera(true);
        selector.count(maxNum);
        selector.multi();
        selector.origin(mSelect);
        selector.start(mActivity, REQUEST_IMAGE);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {

            case 2:
                if (resultCode == RESULT_OK) {

                    select = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);

                    mSelect.clear();
                    for (String s : select) {

                        if (s != "") {
                            Log.e("路径", "路径：" + s);
                            mSelect.add(s);
                        }
                    }
                    adapter.notifyDataSetChanged();
                }
                break;
        }

    }

    @Override
    protected void onDestroy() {

        super.onDestroy();

        if (unbinder != null) {
            unbinder.unbind();
        }

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:
                    upload(mSelect);
                    break;

                case 2:

                    Toast("发布成功");
                    finish();

                    break;

                case 3:

                    Toast("发布失败");
                    break;

            }

        }
    };


    private void upload(List<String> selImageList) {// selImageList 包含图片路径的list

        if (selImageList != null) {

            OkHttpClient okHttpClient = new OkHttpClient();

            MultipartBody.Builder builder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM); //表单上传文件

            for (int i = 0; i < selImageList.size(); i++) {

                if (!selImageList.get(i).equals("")) {
                    File file = new File(new BitmapUtil().compressImage(selImageList.get(i))); //根据路径创建file对象
                    builder.addFormDataPart("image[]",
                            file.getName(),
                            RequestBody.create(MediaType.parse("image/jpeg"), file)
                    );
                }

            }

            List<String> l = new ArrayList<>();
            l.add(editText.getText().toString());

            //post时的参数，后台通过request.getParameter("specialname").toString() 取出
            builder.addFormDataPart("sign", AllUtil.md5(sing(l)));
            builder.addFormDataPart("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
            builder.addFormDataPart("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
            builder.addFormDataPart("ts", System.currentTimeMillis() / 1000 + "");
            builder.addFormDataPart("cmd", "addPost");
            builder.addFormDataPart("data[content]", editText.getText().toString());

            RequestBody requestBody = builder.build();
            Request request = new Request.Builder()
                    .url("http://zmx.123xk.cn/admin/api.bbs/entry")
                    .post(requestBody)
                    .build();

            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("onFailure醋味发信息: ", e.toString());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {

                    try {

                        JSONObject object = new JSONObject(response.body().string());

                        if (object.getString("code").equals("1")) {

                            handler.sendEmptyMessage(2);

                        }else{
                            handler.sendEmptyMessage(3);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            });

        }
    }


    @OnClick(R.id.submit_feedback)
    public void onViewClicked() {

        handler.sendEmptyMessage(1);

    }
}
